package com.example.tse.rbhttpservice.service;

import android.content.Context;
import android.graphics.Bitmap;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.cache.ACache;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.log.L;
import org.kymjs.kjframe.utils.StringUtils;

import java.util.Map;

/**
 * Created by tse on 2015/8/14.
 */
public class HttpService {

    public final static int FromDefault = 0;
    public final static int FromCache = 1;
    public final static int FromNetWork = 2;

    private static String serverDevelope = "http://121.43.115.115:8081/";

    private static Gson gson = new Gson();

    public static String token = "";

    public void post(Context context, final String url, HttpParams params, final Class<? extends RudderResponse> responseClassType, final ResponseServiceListenerT<RudderResponse> callBack) {

        final ACache mCache = ACache.get(context);

        params.putHeaders("UserToken", token);

        final KJHttp kjh = new KJHttp();
        L.d("HttpService", "HttpService post url:" + serverDevelope + url + " HttpService UrlParams():" + params.getUrlParams() + " Headers:" + params.getHeaders());

        kjh.post(serverDevelope + url, params, false, new HttpCallBack() {
            @Override
            public void onPreStart() {
                super.onPreStart();
                callBack.onPreStart();
                String cacheStr = mCache.getAsString(url);
                if (cacheStr == null) {
                    callBack.okData(null, HttpService.FromDefault);
                    return;
                }
                try {
                    String body = new JSONObject(cacheStr).getString("body");
                    RudderResponse response = gson.fromJson(body, responseClassType);
                    callBack.okData(response, HttpService.FromCache);

                } catch (JSONException e) {
                    e.printStackTrace();
                    L.d("HttpService", "HttpService onPreStart e:" + e);
                }
            }

            @Override
            public void onSuccessInAsync(byte[] t) {
                super.onSuccessInAsync(t);
                callBack.onSuccessInAsync(t);


                String data = new String(t);
                L.d("HttpService", " HttpService onSuccessInAsync data:" + data);
                mCache.put(url, data);


                try {

                    if (url.contains("account/login") || url.contains("account/bindMobile") || url.contains("account/authLogin") || url.contains("account/register")) {
                        if (new JSONObject(data).getString("code").equals("0")) {
                            token = new JSONObject(data).getString("message");
                            mCache.put("token", token);
                            L.d("HttpService set token:" + token);
                        }

                    }
//                    responsePost = gson.fromJson(new JSONObject(data).getString("body"), responseClassType);


                } catch (JSONException e) {
                    e.printStackTrace();
                    L.d("HttpService", " HttpService onSuccessInAsync e:" + e);
                }
            }

            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                callBack.onSuccess(t);


                try {
                    RudderResponse responsePost = gson.fromJson(new JSONObject(t).getString("body"), responseClassType);
                    callBack.okData(responsePost, HttpService.FromNetWork);
                    callBack.okData(responsePost);
                    callBack.onMessage(new JSONObject(t).getString("message"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }


                L.d("HttpService", " HttpService onSuccess string t:" + t);
            }

            @Override
            public void onSuccess(Map<String, String> headers, byte[] t) {
                super.onSuccess(headers, t);

                L.d("HttpService", "HttpService onSuccess byte t:" + new String(t));
                callBack.onSuccess(headers, t);
            }

            @Override
            public void onSuccess(Bitmap t) {
                super.onSuccess(t);
                callBack.onSuccess(t);
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                L.d("HttpService", "HttpService onFailure strMsg:" + strMsg);
                callBack.onFailure(errorNo, strMsg);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                callBack.onFinish();
            }

            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
                callBack.onLoading(count, current);
            }
        });
    }


    public void get(Context context, final String url, HttpParams params, final Class<? extends RudderResponse> responseClassType, final ResponseServiceListenerT<RudderResponse> callBack) {


        final ACache mCache = ACache.get(context);


        params.putHeaders("UserToken", token);


        final KJHttp kjh = new KJHttp();
        L.d("HttpService", "HttpService sent url:" + serverDevelope + url + " HttpService UrlParams():" + params.getUrlParams() + " Headers:" + params.getHeaders());


        kjh.get(serverDevelope + url, params, false, new HttpCallBack() {
            @Override
            public void onPreStart() {
                super.onPreStart();
                callBack.onPreStart();

                String cacheStr = mCache.getAsString(url);
                if (cacheStr == null) {
                    callBack.okData(null, HttpService.FromDefault);
                    return;
                }
                L.d("HttpService", "HttpService cacheStr:" + cacheStr);
                L.d("HttpService", "HttpService responseClassType:" + responseClassType);


                try {
                    RudderResponse response = gson.fromJson(new JSONObject(cacheStr).getString("body"), responseClassType);
                    callBack.okData(response, HttpService.FromCache);

                } catch (JSONException e) {
                    e.printStackTrace();
                    L.d("HttpService  e:" + e);

                }
                L.d("HttpService", "HttpService onPreStart:");
            }

            @Override
            public void onSuccessInAsync(byte[] t) {
                super.onSuccessInAsync(t);
                callBack.onSuccessInAsync(t);
                mCache.put(url, new String(t));
            }

            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                callBack.onSuccess(t);

                try {
                    RudderResponse responseGetN = gson.fromJson(new JSONObject(t).getString("body"), responseClassType);
                    callBack.okData(responseGetN, HttpService.FromNetWork);
                    callBack.okData(responseGetN);
                    callBack.onMessage(new JSONObject(t).getString("message"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }


                L.d("HttpService", "HttpService onSuccess t:" + t);
            }

            @Override
            public void onSuccess(Map<String, String> headers, byte[] t) {
                super.onSuccess(headers, t);
                callBack.onSuccess(headers, t);
            }

            @Override
            public void onSuccess(Bitmap t) {
                super.onSuccess(t);
                callBack.onSuccess(t);
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                callBack.onFailure(errorNo, strMsg);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                callBack.onFinish();
            }

            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
                callBack.onLoading(count, current);
            }
        });
    }

    public void getList(Context context, final String url, HttpParams params, final Class<? extends RudderResponse> responseClassType, final ResponseServiceListenerT<RudderResponse> callBack) {


        final ACache mCache = ACache.get(context);
        L.d("HttpService getLis ttoken:" + token);
        params.putHeaders("UserToken", token);

        final KJHttp kjh = new KJHttp();
        L.d("HttpService", "HttpService sent url:" + serverDevelope + url + " HttpService UrlParams():" + params.getUrlParams() + " Headers:" + params.getHeaders());

        kjh.get(serverDevelope + url, params, false, new HttpCallBack() {
            @Override
            public void onPreStart() {
                super.onPreStart();
                callBack.onPreStart();

                String cacheStr = mCache.getAsString(url);
                if (cacheStr == null) {
                    callBack.okData(null, HttpService.FromDefault);
                    return;
                }
                try {
                    RudderResponse response = new RudderResponse();
                    response.setBody(new JSONObject(cacheStr).getString("body"));
                    callBack.okData(response, HttpService.FromCache);
                } catch (JSONException e) {
                    e.printStackTrace();
                    L.d("HttpService", "HttpService e:" + e);
                }
            }

            @Override
            public void onSuccessInAsync(byte[] t) {
                super.onSuccessInAsync(t);
                callBack.onSuccessInAsync(t);
                String data = new String(t);
                L.d("HttpService getList data:" + data);
                mCache.put(url, data);
            }

            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                callBack.onSuccess(t);
                RudderResponse responseGetList;
                try {
                    responseGetList = new RudderResponse();
                    L.d("HttpService new JSONObject(data).getString(body):" + new JSONObject(t).getString("body"));
                    responseGetList.setBody(new JSONObject(t).getString("body"));
                    callBack.okData(responseGetList, HttpService.FromNetWork);
                    callBack.okData(responseGetList);
                    callBack.onMessage(new JSONObject(t).getString("message"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onSuccess(Map<String, String> headers, byte[] t) {
                super.onSuccess(headers, t);
                callBack.onSuccess(headers, t);
            }

            @Override
            public void onSuccess(Bitmap t) {
                super.onSuccess(t);
                callBack.onSuccess(t);
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                callBack.onFailure(errorNo, strMsg);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                callBack.onFinish();
            }

            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
                callBack.onLoading(count, current);
            }
        });
    }


    public boolean isLogin() {
        return !StringUtils.isEmpty(token);
    }

    public static void cleanToken() {
        token = "";
    }

    public static void setToken(String stoken) {
        token = stoken;
    }

    public static String getToken(String token) {
        return token;
    }

}
